package com.supermap.qdsearch.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.supermap.qdsearch.R;
import com.supermap.qdsearch.adapter.FileAdapter;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class FileManageActivity extends AppCompatActivity implements ListView.OnItemClickListener {

    @BindView(R.id.mPath)
    TextView mPath;
    @BindView(android.R.id.list)
    ListView list;
    @BindView(R.id.buttonConfirm)
    Button buttonConfirm;
    @BindView(R.id.buttonCancle)
    Button buttonCancle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private List<String> items = null;
    private List<String> paths = null;
    private String rootPath = "/";
    private String curPath = "/";
    private final static String TAG = "bb";
    int index;

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_file_manage);
        ButterKnife.bind(this);
        //设置toolbar
        toolbar.setTitle("目录选择");
        toolbar.setTitleTextColor(Color.WHITE);
        buttonConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent data = new Intent(FileManageActivity.this, MainActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("file", curPath);
                data.putExtras(bundle);
                setResult(2, data);
                finish();
            }
        });

        buttonCancle.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });
        getFileDir(rootPath);
    }

    private void getFileDir(String filePath) {
        mPath.setText(filePath);
        items = new ArrayList<String>();
        paths = new ArrayList<String>();
        File f = new File(filePath);
        File[] files = f.listFiles();
        if (!filePath.equals(rootPath)) {
            items.add("b1");
            paths.add(rootPath);
            items.add("b2");
            paths.add(f.getParent());
        }
        if(files!=null){
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                items.add(file.getName());
                paths.add(file.getPath());
            }
        }


        list.setAdapter(new FileAdapter(this, items, paths));
        list.setOnItemClickListener(this);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        File file = new File(paths.get(position));
        if (file.isDirectory()) {
            curPath = paths.get(position);
            this.index = position;
            AndPermission.with(this)
                    .requestCode(100)
                    .permission(
                            // 多个权限，以数组的形式传入。
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE
                    )
                    .rationale(rationaleListener)
                    .callback(this)
                    .start();
        } else {
            //可以打开文件
        }
    }


    @PermissionYes(100)
    private void getPermissionYes(List<String> grantedPermissions) {
        // TODO 申请权限成功。
        getFileDir(paths.get(index));
    }

    @PermissionNo(100)
    private void getPermissionNo(List<String> deniedPermissions) {
        // TODO 申请权限失败。

        // 是否有不再提示并拒绝的权限。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {

            // 第二种：用自定义的提示语。
            AndPermission.defaultSettingDialog(this, 400)
                    .setTitle("权限申请失败")
                    .setMessage("您拒绝了我们必要的一些权限，已经没法愉快的玩耍了，请在设置中授权！")
                    .setPositiveButton("去设置")
                    .show();

        }
    }


    /**
     * Rationale支持，这里自定义对话框。
     */
    private RationaleListener rationaleListener = (requestCode, rationale) -> {
        AlertDialog.newBuilder(this)
                .setTitle("友好提醒")
                .setMessage("您已拒绝过读取SDK权限，沒有SDK权限无法使用该功能，请授权！")
                .setPositiveButton("授权", (dialog, which) -> {
                    rationale.resume();
                })
                .setNegativeButton("拒绝", (dialog, which) -> {
                    rationale.cancel();
                }).show();
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 400: { // 这个400就是你上面传入的数字。
                // 你可以在这里检查你需要的权限是否被允许，并做相应的操作。
                getFileDir(paths.get(index));
                break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }
}
